package com.leha.forum.lehare.mapper;

import com.leha.forum.lehare.entity.UserLevel;
import org.apache.ibatis.annotations.*;

import java.util.Date;
import java.util.List;

@Mapper
public interface UserLevelDAO {
    // 1. 新增用户等级关联
    @Insert("INSERT INTO user_levels(user_id, level_id, experience) VALUES(#{userId}, #{levelId}, #{experience})")
    void insert(UserLevel userLevel);

    // 2. 根据user_level_id查询
    @Select("SELECT * FROM user_levels WHERE user_level_id = #{userLevelId}")
    @Results({
            @Result(property = "userLevelId", column = "user_level_id"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "levelId", column = "level_id"),
            @Result(property = "createdAt", column = "created_at"),
            @Result(property = "updatedAt", column = "updated_at")
    })
    UserLevel selectById(Integer userLevelId);

    // 3. 根据user_id查询用户等级信息（包含关联的等级详情）
    @Select("SELECT ul.*, l.level_name, l.min_experience " +
            "FROM user_levels ul " +
            "LEFT JOIN level l ON ul.level_id = l.level_id " +
            "WHERE ul.user_id = #{userId}")
    UserLevel selectByUserIdWithLevel(Integer userId);

    // 4. 根据user_id查询基础用户等级信息
    @Select("SELECT * FROM user_levels WHERE user_id = #{userId}")
    UserLevel selectByUserId(Integer userId);
    @Update("UPDATE user_levels SET level_id=#{levelId}, experience=#{experience} WHERE user_level_id=#{userLevelId}")
    void update(UserLevel userLevel);

    // 5. 更新用户等级ID
    @Update("UPDATE user_levels SET level_id = #{levelId}, updated_at = #{updatedAt} " +
            "WHERE user_level_id = #{userLevelId}")
    void updateLevelId(@Param("userLevelId") Integer userLevelId,
                      @Param("levelId") Integer levelId,
                      @Param("updatedAt") Date updatedAt);

    // 6. 增加用户经验值
    @Update("UPDATE user_levels SET experience = experience + #{points}, updated_at = #{updatedAt} " +
            "WHERE user_id = #{userId}")
    int addExperience(@Param("userId") Integer userId,
                      @Param("points") Integer points,
                      @Param("updatedAt") Date updatedAt);

    // 7. 根据user_id删除记录
    @Delete("DELETE FROM user_levels WHERE user_id = #{userId}")
    int deleteByUserId(Integer userId);

    // 8. 检查用户等级记录是否存在
    @Select("SELECT COUNT(*) FROM user_levels WHERE user_id = #{userId}")
    boolean existsByUserId(Integer userId);

    // 9. 获取所有用户等级信息
    @Select("SELECT ul.*, u.username, l.level_name " +
            "FROM user_levels ul " +
            "JOIN user u ON ul.user_id = u.user_id " +
            "JOIN level l ON ul.level_id = l.level_id")
    List<UserLevel> selectAllWithDetails();
}